import smtplib
import random
import time
from email.mime.text import MIMEText
import string


def get_code(length=6):
    """生成指定长度的验证码"""
    num = '0123456789'  # 数字集0-9
    zi_mu = string.ascii_letters  # 字母集 a-z,A-Z
    easy_code = ''.join(random.choices(num, k=length))  # 生成6位简单密码
    hard_code = ''.join(random.choices(num + zi_mu, k=length))  # 生成6位复杂密码
    print("验证码为：" + easy_code)
    return easy_code


def send_email(re_email, code):
    """发送包含验证码的邮件"""
    sender_email = 'xxxxxx@qq.com'  # 发件人邮箱
    sender_password = 'xxxxxxxxxx'  # 发件人服务授权码
    subject = '验证码'  # 邮件主题

    # 构造邮件内容
    message = MIMEText('这是一封来自python的邮件，登录的验证码为：' + code, 'plain', 'utf-8')  # 参数为(正文内容,文本格式,编码格式)
    message['From'] = sender_email
    message['To'] = re_email
    message['Subject'] = subject

    # 连接到 SMTP 服务器并发送邮件
    # Gmail：stmp.gmail.com:587
    # QQ邮箱：smtp.qq.com:465
    # 163邮箱：stmp.163.com:25
    with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
        server.login(sender_email, sender_password)  # 登录邮箱
        server.sendmail(sender_email, re_email, message.as_string())  # 发送邮件


# 示例用法
if __name__ == "__main__":
    re_email = 'xxxxxxxx@qq.com'  # 收件人邮箱
    code = get_code()  # 获取验证码
    send_email(re_email, code)  # 发邮箱
    print('邮件发送成功')
    time.sleep(0.5)